#include "Events.h"
#include "RandomSystem.h"

#include <cassert>

namespace
{

inline void ReadFileLine(STD::ifstream& i_fstream, STL::string& o_line)
{
	static const size_t BUFFER_SIZE = 256;
	static char buffer[BUFFER_SIZE];
	do{
		i_fstream.getline(buffer, BUFFER_SIZE);
		o_line = buffer;
	}while(o_line.empty());
}

}

EventGenerator::EventGenerator(const STL::string& i_filename)
{
	ParseEventMessages(i_filename);
}

void EventGenerator::ParseEventMessages(const STL::string& i_filename)
{
	STD::ifstream fileStream;
	fileStream.open(i_filename.c_str(), STD::ifstream::in);

	if (fileStream.fail())
	{
		STD::cout << "ERROR" << STD::endl;
		assert(0);
	}

	STL::string line;
	ReadFileLine(fileStream,line);

	while (fileStream.good() && line != "#eof")
	{		
		assert(line[0] == '#');
		const STL::string category = line.substr(1, line.length()-1);

		STL::vector<STL::string>& sentences = m_eventMessages[category];
		ReadFileLine(fileStream,line);
		while(line.at(0) != '#')
		{
			sentences.push_back(line);
			ReadFileLine(fileStream,line);
		}
	}
}

const STL::string& EventGenerator::RandomEventMessageInCategory(const STL::string& i_category, const STL::string& i_first, const STL::string& i_second) const
{
	static char s_arrayMessage[256];
	static STL::string s_event;

	EventMap::const_iterator cit = m_eventMessages.find(i_category);
	assert(cit != m_eventMessages.end() && "categoria di evento inesistente");

	const STL::vector<STL::string>& messages = cit->second;

	const int random = Rand() % messages.size();
	const STL::string& message = messages[random];
	size_t length = message.length() + i_first.length() + i_second.length() + 1;
	sprintf_s(s_arrayMessage, length, message.c_str(), i_first.c_str(), i_second.c_str());
	s_event.assign(s_arrayMessage);
	
	return s_event;
}

const STL::string& EventGenerator::RandomEventMessageInCategory(const STL::string& i_category, const STL::string& i_name) const
{
	static char s_arrayMessage[256];
	static STL::string s_event;

	EventMap::const_iterator cit = m_eventMessages.find(i_category);
	assert(cit != m_eventMessages.end() && "categoria di evento inesistente");

	const STL::vector<STL::string>& messages = cit->second;

	const int random = Rand() % messages.size();
	const STL::string& message = messages[random];
	size_t length = message.length() + i_name.length() + 1;
	sprintf_s(s_arrayMessage, length, message.c_str(), i_name.c_str());
	s_event.assign(s_arrayMessage);
	
	return s_event;
}

const STL::string& EventGenerator::RandomEventMessageInCategory(const STL::string& i_category) const
{
	EventMap::const_iterator cit = m_eventMessages.find(i_category);
	assert(cit != m_eventMessages.end() && "categoria di evento inesistente");
	const STL::vector<STL::string>& messages = cit->second;
	const int random = Rand()%messages.size();

	return messages[random];
}
